package com.xidian.zhiancloud.util.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xidian.zhiancloud.util.constants.WeChatContants;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @program: baseframe
 * @description: 微信工具类
 * @author: miyaxin
 * @create: 2020-07-16 11:28
 **/
public class WeChatUtil {

    /**
     * 验证签名
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[] { WeChatContants.TOKEN, timestamp, nonce };
        // 将token、timestamp、nonce三个参数进行字典序排序
        // Arrays.sort(arr);
        sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        content = null;
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * @param requestUrl 微信上传临时素材的接口url
     * @param file       要上传的文件
     * @return String  上传成功后，微信服务器返回的消息
     * @desc ：微信上传素材的请求方法
     */
    public static String httpRequest(String requestUrl, File file) {
        StringBuffer buffer =new StringBuffer();

        try {
            //1.建立连接
            URL url =new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); //打开链接

            //1.1输入输出设置
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false);// post方式不能使用缓存
            //1.2设置请求头信息
            httpUrlConn.setRequestProperty("Connection","Keep-Alive");
            httpUrlConn.setRequestProperty("Charset","UTF-8");
            //1.3设置边界
            String BOUNDARY ="----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);

            // 请求正文信息
            // 第一部分：
            //2.将文件头输出到微信服务器
            StringBuilder sb =new StringBuilder();
            sb.append("--");// 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
                    +"\";filename=\"" + file.getName() +"\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 获得输出流
            OutputStream outputStream =new DataOutputStream(httpUrlConn.getOutputStream());
            // 将表头写入输出流中：输出表头
            outputStream.write(head);

            //3.将文件正文部分输出到微信服务器
            // 把文件以流文件的方式 写入到微信服务器中
            DataInputStream in =new DataInputStream(new FileInputStream(file));
            int bytes =0;
            byte[] bufferOut =new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut,0, bytes);
            }
            in.close();
            //4.将结尾部分输出到微信服务器
            byte[] foot = ("\r\n--" + BOUNDARY +"--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            outputStream.write(foot);
            outputStream.flush();
            outputStream.close();

            //5.将微信服务器返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader =new InputStreamReader(inputStream,"utf-8");
            BufferedReader bufferedReader =new BufferedReader(inputStreamReader);

            String str =null;
            while ((str = bufferedReader.readLine()) !=null) {
                buffer.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream =null;
            httpUrlConn.disconnect();


        }catch (IOException e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        //4.json字符串转对象：解析返回值，json反序列化
        String result = buffer.toString().replaceAll("[\\\\]","");
        System.out.println("result:" + result);
        JSONObject resultJSON = JSONObject.parseObject(result);
        return resultJSON.getString("media_id");
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }

    private static void sort(String a[]) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[j].compareTo(a[i]) < 0) {
                    String temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
    }

    @SuppressWarnings("rawtypes")
	public static String mapToXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        mapToXML2(map, sb);
        sb.append("</xml>");
        try {
            return sb.toString();
        } catch (Exception e) {
        }
        return null;
    }

    @SuppressWarnings("rawtypes")
	private static void mapToXML2(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value) {
                value = "";
            }
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
                sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
                    mapToXML2(hm, sb);
                }
                sb.append("</" + key + ">");

            } else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
                    mapToXML2((HashMap) value, sb);
                    sb.append("</" + key + ">");
                } else {
                    sb.append("<" + key + "><![CDATA[" + value + "]]></" + key + ">");
                }

            }

        }
    }
    /**
     * 回复文本消息
     * @param requestMap
     * @param content
     * @return
     */
    public static String sendTextMsg(Map<String,String> requestMap,String content){

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("ToUserName", requestMap.get(WeChatContants.FromUserName));
        map.put("FromUserName", requestMap.get(WeChatContants.ToUserName));
        map.put("MsgType", WeChatContants.RESP_MESSAGE_TYPE_TEXT);
        map.put("CreateTime", System.currentTimeMillis());
        map.put("Content", content);
        return mapToXML(map);
    }
    /**
     * 回复图片信息
     * @param requestMap openId 用户openId  media_id微信服务器图片 url 回复消息接口
     * @return
     */
    public static String sendArticleMsg(Map<String,String> requestMap){
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("touser", requestMap.get("openId"));
        map.put("msgtype", "image");
        Map<String,Object> map1 = new HashMap<String, Object>();
        map1.put("media_id", requestMap.get("media_id"));
        map.put("image",map1);
        System.out.println(JSON.toJSONString(map));
        String urlBuffer = HttpUtil.sendPost(requestMap.get("url"), JSON.toJSONString(map));
        JSONObject jsonObject = JSONObject.parseObject(urlBuffer);
        if (null!=urlBuffer) {
            return jsonObject.toString();
        }else{
            return "服务消息失败";
        }
    }
}
